package com.cloud.shopping.pay.mq;

import com.alibaba.fastjson.JSON;
import com.cloud.shopping.constants.RocketConstants;
import com.cloud.shopping.pay.model.PayLog;
import com.cloud.shopping.pay.service.PayLogService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author John.zhang
 * @version Id: TransactionListener, v 1.0 2021/1/5 10:17 ZhiYong Exp $
 */

@Component
@RocketMQTransactionListener(txProducerGroup = RocketConstants.PRODUCER_GROUP)
public class TransactionListener implements RocketMQLocalTransactionListener {

    @Resource
    private PayLogService payLogService;


    /**
     * 当向RocketMQ的Broker发送Half消息成功之后，调用该方法
     * @param message 发送的消息
     * @param o 额外参数
     * @return RocketMQLocalTransactionState
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //消息
            String result = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            PayLog payLog = JSON.parseObject(result,PayLog.class);
            payLogService.add(payLog);
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 超时回查
     * @param message message
     * @return RocketMQLocalTransactionState
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return RocketMQLocalTransactionState.COMMIT;
    }
}
